﻿using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Xml.Linq;
using WebApplication1.Controllers;
using WebApplication1.Model;
using WebApplication1.Service;

namespace WebApplication1.chat
{
    public class VideoHub:Hub<INotityVideo>
    {
        public VideoHub(ChatService chatService)
        {
            ChatService = chatService;
        }
        //public static List<UserModel> Names { get; set; } = new List<UserModel>();
        public ChatService ChatService { get; }
        public override async Task OnConnectedAsync()
        {
            var httpContext = Context.GetHttpContext();//获取httpcontext
            var allUser = ChatService.GetAllUser();//拿到当前所有用户的列表
            var name = httpContext.Request.Query["name"];//拿到用户设置的参数
            if (!string.IsNullOrWhiteSpace(name)&&!allUser.Any(s=>s.Name==name))//判断是否有同名用户 没有同名才可以添加
            {
                ChatService.AddUser(new UserModel { Id = Context.ConnectionId, Name = name });//添加用户
                await Clients.All.UserChange(ChatService.GetAllUser());//通知前端在线用户的变更
            }
           await base.OnConnectedAsync();
        }
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            var httpContext = Context.GetHttpContext();//获取httpcontext
            var name = httpContext.Request.Query["name"];//拿到当前所有用户的列表
            var allUser = ChatService.GetAllUser();
            var index= allUser.FirstOrDefault(x => x.Name == name);//判断用户列表中是否有这个人
            if (index != null)
            {
                allUser.Remove(index);//存在就删除这个用户
            }
            var singleData = ChatService.GetSingleChat();
            if (singleData != null)
            {
                if (singleData.Any(s => s.Value.Any(a => a.app.Contains(name))))
                {
                    var singleModel = singleData.FirstOrDefault(s => s.Value.Any(a => a.app.Contains(name)));
                    var names = singleModel.Key.Replace("single", "");//根据single分割 找到单聊的两个人的名字
                    var Allname = names.Split("And");
                    var notityName = Allname.FirstOrDefault(s => s != name);
                    var user = ChatService.GetAllUser().FirstOrDefault(s => s.Name == notityName);//找到是否存在这个用户
                    if (user != null)
                    {
                        await Clients.Client(user.Id).CloseChat();//通知这个用户退出聊天
                    }
                    singleData.Remove(singleModel.Key);
                }
            }
            var group = ChatService.GetGroupChat();
            if (group != null)
            {
                if (group.Any(s => s.Value.AllUsers.Any(a => a.Name == name)))
                {
                    var groupModel = group.FirstOrDefault(s => s.Value.AllUsers.Any(a => a.Name == name));
                    groupModel.Value.AllUsers.RemoveAt(groupModel.Value.AllUsers.FindIndex(a => a.Name == name));
                    if (groupModel.Value.AllUsers.Count == 0)
                    {
                        ChatService.GetGroupChat().Remove(groupModel.Value.Name);//如果群组没人了，就移除这个群组
                    }
                    await Clients.All.GroupChange(group.Values.ToList());//通知前端群组的变更
                }
            }
            var share = ChatService.GetShare();
            if (share != null)
            {
                if (share.Any(s => s.Value.AllUsers.Any(a => a.Name == name)))
                {
                    var shareModel = share.FirstOrDefault(s => s.Value.AllUsers.Any(a => a.Name == name));
                    shareModel.Value.AllUsers.RemoveAt(shareModel.Value.AllUsers.FindIndex(a => a.Name == name));
                    if (shareModel.Value.AllUsers.Count == 0)
                    {
                        ChatService.GetShare().Remove(shareModel.Value.Name);//如果群组没人了，就移除这个群组
                    }
                    await Clients.All.ShareChange(share.Values.ToList());//通知前端群组的变更
                }
            }
            await Clients.All.UserChange(allUser);//通知前端在线用户的变更
            await base.OnDisconnectedAsync(exception);
        }
    }
}
